using UnityEngine;

namespace GameToolkit.BehaviourTree
{
    [System.Serializable]
    [CompositeTitle("选择器", Description = "Selector")]
    [CompositeCategory]
    [CompositeIcon("0e8ec6657914e714196e16340921a10f")]
    [JsonImporter(FormerlySerializedAs = "BTSelector")]
    public class Selector : ExecutableComposite
    {
        public override BehaviourTreeObject Create()
        {
            return new Impl();
        }

        class Impl : ControllerNode
        {
            int mNextIndex;

            protected override void OnCreate(BehaviourTreePlayer player)
            {
            }

            protected override void OnDestroy(BehaviourTreePlayer player)
            {
            }

            protected override NodeState GetNextBehaviour(BehaviourTreePlayer player, out ExecutableEntry nextNode)
            {
                var prev = mNextIndex - 1;
                if (prev >= 0 && GetChild(prev).State == NodeState.Success)
                {
                    nextNode = null;
                    return NodeState.Success;
                }
                if (mNextIndex < ChildCount)
                {
                    nextNode = GetChild(mNextIndex++);
                    return NodeState.Running;
                }
                else
                {
                    nextNode = null;
                    return NodeState.Failed;
                }
            }

            protected override void OnStart(BehaviourTreePlayer player)
            {
                mNextIndex = 0;
            }

            protected override void OnStop(BehaviourTreePlayer player)
            {

            }
        }
    }
}
